package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"runtime"
	"strings"
)

// 注册机 CMD版本
func RegisterMachineCMD() {
	mc, ets, api_info := ReadUserInput()
	r_string := GetRandomString()
	fmt.Println(111111111, api_info)
	active_code := GenerateActiveCode(mc + ets + api_info + r_string)
	fmt.Println(active_code)
}

//判别系统后读取用户输入信息
func ReadUserInput() (machine_code string, expire_time_str string, api_info string) {
	fmt.Println("wy license register machine")
	fmt.Println("---------------------")
	fmt.Println("---------------------")
	//机器码获取
	mc_reader := bufio.NewScanner(os.Stdin)
	fmt.Print("please input machine code\n\r", " -> ")
	mc_reader.Scan()
	machine_code = mc_reader.Text()
	// convert CRLF to LF
	machine_code = CRLFToLF(machine_code)
	if len(machine_code) != 16 {
		log.Fatal("machine_code error")
	}
	//过期时间获取
	et_reader := bufio.NewScanner(os.Stdin)
	fmt.Print("please choose expire time (1.one day\t2.one week\t3.one month\t4.one year\t5.permanent)\n\r", " -> ")
	et_reader.Scan()
	expire_time := et_reader.Text()
	expire_time = CRLFToLF(expire_time)
	switch expire_time {
	case "1":
		expire_time_str = "E"
	case "2":
		expire_time_str = "X"
	case "3":
		expire_time_str = "N"
	case "4":
		expire_time_str = "P"
	case "5":
		expire_time_str = "Q"
	default:
		log.Fatal("time params error")
	}

	// 先读取文件，因为API_INFO如果手动输入则只能最大输入4096byte，不能满足大部分需求
	if CheckFileIsExist("API_INFO.txt") {
		api_info = ReadFile("API_INFO.txt")
	} else {
		api_reader := bufio.NewScanner(os.Stdin)
		fmt.Print("please input system API info \n\r", " -> ")
		api_reader.Scan()
		api_info = api_reader.Text()
		if len(api_info) >= 4095 {
			log.Fatal("string length limited 4095, input is too long, might missing some string")
		}
		api_info = CRLFToLF(api_info)
	}
	return machine_code, expire_time_str, api_info
}

func CRLFToLF(text string) string {
	// 判定系统类型 linux or windows
	sysType := runtime.GOOS

	if sysType == "linux" {
		// LINUX系统
		return strings.Replace(text, "\n", "", -1)
	}
	if sysType == "windows" {
		// windows系统
		return strings.Replace(text, "\r\n", "", -1)
	}
	log.Fatal("system error")
	return ""
}

func GenerateActiveCode(text string) string {
	secret_key := GetMD5Encode(SecreteKey)
	var key = []byte(secret_key)
	text, ok := AESEncrypt(key, text)
	fmt.Println("AESEncrypt activecode   ", text)
	if !ok {
		log.Fatal("encrypt is failed")
	}
	return text
}
